<template>
  <view class="collect">
    <view class="top uni-px-10">
      <view class="stat">
        <text>共</text>
        <text class="count uni-mx-5">{{ showStatNumber }}</text>
        <text>件商品</text>
      </view>
      <view class="operation" @tap="state.auxiliary.activeEdit = !state.auxiliary.activeEdit">
        <text>{{operationTxt}}</text>
      </view>
    </view>
    <scroll-view scroll-y class="scroll" :style="{height: scrollDynamicHeight + 'px'}" @scrolltolower="loadMore">
      <view class="product-list">
        <uni-swipe-action>
          <uni-swipe-action-item
              :right-options="state.swipeConfig.option"
              :show="state.swipeConfig.show[idx]"
              :auto-close="true"
              @click="clickSwipeAction($event, idx)"
              v-for="(forItem, idx) in state.productList" :key="idx"
          >
            <view class="product-item uni-mb-5">
              <view class="selector" v-if="state.auxiliary.activeEdit">
                <checkbox-group @change="clickCheckbox($event, forItem.product.skuId)">
                  <checkbox :checked="forItem.selected" :value="forItem.product.skuId + ''" ></checkbox>
                </checkbox-group>
              </view>
              <view class="product-info">
                <view class="image uni-mr-5">
                  <navigator :url="'/pages/goods/goods?id=' +forItem.product.skuId">
                    <image style="width: 100%; height: 110px;" mode="scaleToFill" :src="forItem.product.thumbCover"></image>
                  </navigator>
                </view>
                <view class="info">
                  <navigator :url="'/pages/goods/goods?id=' +forItem.product.skuId">
                    <view class="name">
                      <text class="product-item-name">{{forItem.product.title }}</text>
                    </view>
                    <view class="title">
                      <text class="product-item-title">{{forItem.product.spec }}</text>
                    </view>
                  </navigator>
                  <view class="aggregation">
                    <view class="price">
                      <text class="product-item-price">￥ {{forItem.product.price }}</text>
                    </view>
                    <view class="sales">
                      <text class="product-item-sales">已售 {{forItem.product.sales}}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <uni-load-more :status="state.auxiliary.loadMore.status"></uni-load-more>
    </scroll-view>
    <view class="bottom uni-pr-10 uni-pl-2" v-if="state.auxiliary.activeEdit">
      <view class="all">
        <checkbox :checked="state.allSelected" value="all" @tap="selectAllChange">全部</checkbox>
      </view>
      <view class="operation-btn">
        <view class="btn-item"><button type="warn" size="mini" @tap="delSelected">删除</button></view>
        <view class="btn-item uni-ml-5"><button type="warn" size="mini" @tap="clearCollect">清空</button></view>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import {computed, ref} from "vue";
import type {ProductItemSelectableType} from "@/types/product";
import {EditableCl} from "@/types/productcls";
import type {PageQueryType} from "@/types/global";
import {getUserCollectProductList, getUserHistoryProductList, getUserTrace} from "@/services/user";
import {onLoad} from "@dcloudio/uni-app";
import type {UserTraceStatType} from "@/types/user";

const props = defineProps({
  sourceType: {
    required: true, type: EditableCl
  }
})

const {windowHeight} = uni.getSystemInfoSync()

const state = ref({
  productList: [] as Array<ProductItemSelectableType>,
  auxiliary: {
    activeEdit: false,
    cancelCollectIds: [] as Array<Number>,
    loadMore: {
      status: "loading" as "more" | "loading" | "no-more",
      finish: false
    },
    stat: {} as UserTraceStatType
  },
  allSelected: false,
  clear: false,
  swipeConfig: {
    show: [] as string[],
    option: [
      {
        text: '删除',
        style: {
          backgroundColor: '#F56C6C'
        }
      }
    ]
  },
  query: {
    page: {
      page: 1,
      size: 10,
      orders: []
    } as PageQueryType
  }
})

/**
 * 获取列表数据
 */
const getListData =async () => {
  if (state.value.auxiliary.loadMore.finish) {
    return
  }
  if (props.sourceType?.sourceType === undefined) {
    return
  }
  let maxPage = 0
  state.value.auxiliary.loadMore.status = "loading"
  switch (props.sourceType?.sourceType) {
    case "history":
      await getUserHistoryProductList(state.value.query.page).then((r) => {
        for (let i = 0; i < r.data.list.length; i++) {
          let refactorItem: ProductItemSelectableType = <ProductItemSelectableType>r.data.list[i]
          refactorItem.selected = false
          state.value.productList.push(refactorItem)
          state.value.swipeConfig.show.push("none")
        }
        maxPage = r.data.pages
      }).catch(() => {
        state.value.auxiliary.loadMore.status = "no-more"
        state.value.auxiliary.loadMore.finish = true
      })
      break
    case "collect":
      await getUserCollectProductList(state.value.query.page).then((r) => {
        for (let i = 0; i < r.data.list.length; i++) {
          let refactorItem: ProductItemSelectableType = <ProductItemSelectableType>r.data.list[i]
          refactorItem.selected = false
          state.value.productList.push(refactorItem)
          state.value.swipeConfig.show.push("none")
        }
        maxPage = r.data.pages
      }).catch(() => {
        state.value.auxiliary.loadMore.status = "no-more"
        state.value.auxiliary.loadMore.finish = true
      })
      break
    default:
  }
  if (maxPage < state.value.query.page.page) {
    state.value.auxiliary.loadMore.status = "no-more"
    state.value.auxiliary.loadMore.finish = true
  } else {
    state.value.auxiliary.loadMore.status = "more"
  }
}
/**
 * 加载下一页
 */
const loadMore = () => {
  state.value.query.page.page += 1
  getListData()
}
/**
 * 点击左滑交互按钮
 * @param e
 * @param idx
 */
const clickSwipeAction = (e: any, idx: number) => {
  console.log("click swipe item: ", e, idx)
  if (e.index === 0) {
    uni.showToast({
      title: "点击了 收藏",
      icon: "none"
    })
  } else {
    uni.showToast({
      title: "点击了 删除",
      icon: "none"
    })
  }
}
/**
 * 编辑场景下选中选择框
 * @param e
 * @param skuId
 */
const clickCheckbox = (e: any, skuId: number) => {
  console.log("component click checkbox: ", e.detail.value, props.sourceType)
  state.value.productList.forEach((v) => {
    if (v.skuId === skuId) {
      v.selected = true
    }
  })
}
/**
 * 删除选中的条目
 */
const delSelected = () => {
  state.value.productList = state.value.productList.filter((v, idx) => {
    if (v.selected) {
      // 同时删除swipe组件中show的参数值
      state.value.swipeConfig.show.splice(idx, 1)
    }
    return v.selected === false
  })
  // 加载下一页
  loadMore()
  // 取消全选
  if (state.value.allSelected) {
    state.value.allSelected = false
  }
}
/**
 * 全选
 */
const selectAllChange = () => {
  console.log("点击了全选 ", state.value.allSelected)
  uni.showToast({
    title: "点击了全选",
    icon: "none"
  })
  // 操作所有的购物车选项
  state.value.allSelected = !state.value.allSelected
  if (state.value.allSelected) {
    // 选中
    state.value.productList.forEach((v) => {
      v.selected = true
    })
  } else {
    // 取消选择
    state.value.productList.forEach((v) => {
      v.selected = false
    })
  }
}
/**
 * 清空
 */
const clearCollect = () => {
  state.value.productList = []
  state.value.swipeConfig.show = []
  state.value.auxiliary.loadMore.status = "no-more"
  state.value.clear = true
}

const operationTxt = computed(() => {
  if (state.value.auxiliary.activeEdit) {
    return "完成"
  }
  return "编辑"
})
const scrollDynamicHeight = computed(() => {
  if (state.value.auxiliary.activeEdit) {
    return windowHeight - 44 - 50 - 50
  }
  return windowHeight - 44 - 50
})

const getTraceStatData = () => {
  // 获取用户足迹的统计数据
  getUserTrace().then((r) => {
    state.value.auxiliary.stat = r.data
  })
}

const showStatNumber = computed(() => {
  if (state.value.clear) {
    return 0
  }
  if (props.sourceType!.sourceType === 'history') {
    return state.value.auxiliary.stat.historyCount
  }
  return state.value.auxiliary.stat.collectCount
})

onLoad(() => {
  console.log("@reload page#EditableProductList", JSON.stringify(props.sourceType))
  getListData()
  getTraceStatData()
})
</script>
<style scoped lang="scss">
.collect {
  .top {
    background-color: #fff;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .stat {
      font-size: 14px;

      .count {
        font-size: 16px;
        color: $uni-color-error;
      }
    }

    .operation {
      color: $uni-color-error;
    }
  }

  .scroll {
    .product-list {
      padding: 0 5px;
      overflow-y: scroll;

      .product-item {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        .product-info {
          display: flex;
          justify-content: space-between;
          width: 100%;
          .image {
            width: 40%;
          }

          .info {
            width: 60%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .product-item-name {
              font-weight: bold;
              font-size: 14px;
              margin-bottom: 10px;
              display: -webkit-box; /* 必须指定为 box */
              -webkit-box-orient: vertical; /* 设置垂直布局 */
              overflow: hidden;
              text-overflow: ellipsis;
              -webkit-line-clamp: 1; /* 限制为两行 */
            }

            .product-item-title {
              font-size: 12px;
              color: #8f939c;
              margin-bottom: 10px;
              display: -webkit-box; /* 必须指定为 box */
              -webkit-box-orient: vertical; /* 设置垂直布局 */
              overflow: hidden;
              text-overflow: ellipsis;
              -webkit-line-clamp: 2; /* 限制为两行 */
            }

            .aggregation {
              display: flex;
              flex-direction: row;
              justify-content: space-between;

              .product-item-price {
                color: #e43d33;
                font-size: 14px;
              }

              .product-item-sales {
                color: #8f939c;
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }
  .bottom {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .operation-btn {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>